const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const request = (method, options = {}) => {
  let token = wx.getStorageSync('token')
  const {
    api,
    data,
    success,
    fail,
    loading,
    loadingText,
    serialize,
    codeFail,
    headers
  } = options

  const url = baseUrl + api

  if (!url) return wx.showToast({
    title: '必须包含请求URL',
  })

  loading && wx.showLoading({
    title: loadingText || 'loading',
  })


  let contentType = 'application/json'
  if (serialize) contentType = 'application/x-www-form-urlencoded'

  const req = wx.request({
    url, // 仅为示例，并非真实的接口地址
    data: data,
    method,
    header: {
      'content-type': contentType,
      'token': token, // 默认值
      ...headers
    },
    timeout: 60000,
    success(res) {
      loading && wx.hideLoading()
      wx.stopPullDownRefresh()

      const {data, code, msg} = res.data

      if (res.statusCode === 401) return logout()
      if (code === '1004') return logout()

      if ([200, '0000'].includes(code)) {
        success && success(res)
      } else {
        wx.showToast({
          title: msg || '网络错误，请稍后重试',
          icon: 'none'
        })
        fail && fail(error)
      }
    
    },
    fail(error) {
      wx.stopPullDownRefresh()
      wx.hideLoading()
      wx.showToast({
        title: '网络错误，请稍后重试',
        icon: 'none'
      })
    },
    complete() {}
  })

  return req
}

const get = request.bind(null, 'GET')
const post = request.bind(null, 'POST')

module.exports = {
  post, get, formatTime
}
